package com.cloudspace.jindun.adapter;

import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.error.VolleyError;
import com.cloudspace.jindun.JindunApp;
import com.cloudspace.jindun.R;
import com.cloudspace.jindun.activity.interphone.ChangeChannelActivity;
import com.cloudspace.jindun.callback.AuthCodeInputCallback;
import com.cloudspace.jindun.model.ChannelInfo;
import com.cloudspace.jindun.model.CommonResult;
import com.cloudspace.jindun.network.api.API;
import com.cloudspace.jindun.network.base.ApiCallback;
import com.cloudspace.jindun.ui.AuthDialog;
import com.cloudspace.jindun.utils.ObjUtil;
import com.cloudspace.jindun.utils.ToastMaker;

import org.apache.http.HttpStatus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static android.app.Activity.RESULT_OK;

/**
 * Created by zengxianhua on 17/1/25.
 */

public class ChangeChannelAdapter extends BaseAdapter{
    public static final String TAG = ChangeChannelAdapter.class.getSimpleName();

    private List<ChannelInfo> datas = new ArrayList<>();
    private View.OnClickListener channelInListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.getTag(R.id.change_channel_info) == null){
                return;
            }

            ChannelInfo info = (ChannelInfo) v.getTag(R.id.change_channel_info);
            boolean hasAccess = "0001".equals(info.isln);
            boolean noPassword = "####".equals(info.channelPass);

            if (hasAccess || noPassword){
                if (hasAccess){
                    directChangeChannel(info);
                }else{
                    enterChannel(info, "####");
                }

            }else{
                showEnterChannelDialog(info);
            }

        }
    };

    private void directChangeChannel(final ChannelInfo info) {
        API.getInstance().getChannelApi().enterChannel(TAG, info.channelId, new ApiCallback<CommonResult>() {
            @Override
            public void handleResult(CommonResult result, VolleyError error) {
                if (result != null && result.status == HttpStatus.SC_OK){
                    selectChangeChannel(info);
                }else{
                    ToastMaker.showToastShort(R.string.generic_error);
                }
            }
        }.toastActionError());
    }

    private void selectChangeChannel(ChannelInfo info){
        String channelId = info.channelId;
        Intent intent = new Intent();

        intent.putExtra("channelid", channelId);
        changeChannelActivity.setResult(RESULT_OK, intent);
        changeChannelActivity.finish();
    }

    private void showEnterChannelDialog(final ChannelInfo info) {
        if (mEnterChannelPasswordDlg == null){
            mEnterChannelPasswordDlg = new AuthDialog(changeChannelActivity);
        }

        mEnterChannelPasswordDlg.show(new AuthCodeInputCallback() {
            @Override
            public void onFinish(String code) {
                if (!TextUtils.equals(info.channelPass, code)){
                    ToastMaker.showToastShort(R.string.channel_input_password_notvalid);
                    return;
                }

                enterChannel(info, code);
            }

            @Override
            public void onCancel() {

            }
        });
    }

    private AuthDialog mEnterChannelPasswordDlg;

    private void enterChannel(final ChannelInfo info, String password) {
            API.getInstance().getChannelApi().joinChannel(TAG, info.channelId, password, new ApiCallback<CommonResult>() {
                @Override
                public void handleResult(CommonResult result, VolleyError error) {
                    if (result != null && result.status == HttpStatus.SC_OK){
                        if (mEnterChannelPasswordDlg != null){
                            mEnterChannelPasswordDlg.hide();
                        }

                        ToastMaker.showToastShort(JindunApp.getInstance().getResources().getString(R.string.enter_channel_success));
                        selectChangeChannel(info);
                    }else {
                        ToastMaker.showToastShort(JindunApp.getInstance().getResources().getString(R.string.enter_channel_error) +
                                ((result != null) ? result.msg : ((error != null) ? error.getMessage():"")));
                    }
                }
            });
    }

    public List<ChannelInfo> getData(){
        return datas;
    }

    private ChangeChannelActivity changeChannelActivity;
    private String mCurrentChannelId;
    private boolean hasCurrentChannel;

    public void setDatas(List<ChannelInfo> data, ChangeChannelActivity context, String currentChannelId){
        mCurrentChannelId = currentChannelId;
        hasCurrentChannel = false;

        moveCurrentChannelToFirst(data, currentChannelId);

        this.datas.clear();
        datas.addAll(data);
        changeChannelActivity = context;
        notifyDataSetChanged();
    }

    private void moveCurrentChannelToFirst(List<ChannelInfo> data, String currentChannelId) {
        if (TextUtils.isEmpty(currentChannelId) ||
                ObjUtil.isEmpty(data)){
            return;
        }

        int index = -1;
        for (int i = 0; i < data.size(); ++i){
            if (data.get(i) != null && data.get(i).channelId.equals(currentChannelId)){
                index = i;
                break;
            }
        }

        if (index != -1){
            hasCurrentChannel = true;
            Collections.swap(data, 0, index);
        }
    }

    @Override
    public int getCount() {
        if (ObjUtil.isEmpty(datas)){
            return 0;
        }
        return datas.size();
    }

    @Override
    public Object getItem(int position) {
        if (getCount() == 0 || position >= getCount() || position < 0){
            return null;
        }
        return datas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Holder holder = null;
        if (convertView == null){
            convertView = LayoutInflater.from(JindunApp.getInstance()).inflate(
                    R.layout.item_channel_list, null);
            holder = new Holder();
            holder.channelIdTv = (TextView) convertView.findViewById(R.id.channelId);
            holder.channelNameTv = (TextView) convertView.findViewById(R.id.channelName);
            holder.inIconImg = (ImageView) convertView.findViewById(R.id.inIcon);
            holder.channelTip = (TextView) convertView.findViewById(R.id.channelTip);
            holder.channelIn = convertView.findViewById(R.id.infl);

            convertView.setTag(holder);
        }

        holder = (Holder) convertView.getTag();

        ChannelInfo info = datas.get(position);
        holder.channelIdTv.setText(String.valueOf(info.channelId));
        holder.channelNameTv.setText(String.valueOf(info.channelName));

        convertView.setTag(R.id.change_channel_info, info);
        convertView.setOnClickListener(channelInListener);

        int currentChannelIndex = hasCurrentChannel ? 0 : -1;

        boolean isChannelIn = "0001".equals(info.isln);

        if (hasCurrentChannel && position == 0){
            holder.channelNameTv.setTextColor(changeChannelActivity.getResources().getColor(R.color.base_color_red));
            holder.inIconImg.setImageResource(R.drawable.channel_report);
        }else{
            holder.channelNameTv.setTextColor(changeChannelActivity.getResources().getColor(R.color.color_999999));

            boolean hasPass = !TextUtils.equals("####", info.channelPass);

            if (hasPass && !isChannelIn){
                holder.inIconImg.setVisibility(View.VISIBLE);
                holder.inIconImg.setImageResource(R.drawable.channel_password);
            }else {
                holder.inIconImg.setVisibility(View.GONE);
            }
        }

        if (position == currentChannelIndex + 1){
            holder.channelTip.setVisibility(View.VISIBLE);
            holder.channelTip.setText(JindunApp.getInstance().getResources().getString(R.string.channel_newmost));
        }else if (position == currentChannelIndex + 5){
            holder.channelTip.setVisibility(View.VISIBLE);
            holder.channelTip.setText(JindunApp.getInstance().getResources().getString(R.string.channel_all));
        }else{
            holder.channelTip.setVisibility(View.GONE);
        }

        return convertView;
    }

    static class Holder{
        public TextView channelNameTv;
        public TextView channelIdTv;
        public View channelIn;
        public ImageView inIconImg;
        public TextView channelTip;
    }
}
